package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.feign.client.ArticleFeignClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ArticleFeignClient articleFeignClient;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    @Autowired
    private Tess4jClient tess4jClient;

    /**
     * 自媒体文章审核---主方法
     *
     * @param newsId 自媒体文章id
     */
    @Override
    @Transactional
    @Async//自动审核的注解  异步方法
    public void autoScanWmNews(Integer newsId) {
        //1.根据文章id去查询wm_news表
        WmNews wmNews = wmNewsMapper.selectById(newsId);
        if (wmNews == null) {
            return;
        }
        //1.5 要对当前文本和图片进行抽取
        Map<String, Object> map = chouquImageAndTextFromWmNews(wmNews);

        //1.6现进行自管理敏感词的审核
        boolean SensitiveScanFlag = sensitiveScan(wmNews, (String) map.get("content"));
        if (!SensitiveScanFlag) {
            return;
        }

        //2.进行文本审核
        boolean textScanFlag = textScan(wmNews, (String) map.get("content"));
        if (!textScanFlag) {
            return;
        }
        //3.进行图片审核
        boolean imageScanFlag = imageScan(wmNews, (List<String>) map.get("imageList"));
        if (!imageScanFlag) {
            return;
        }

        //4.远程调用Feign接口实现保存app端三剑客
        ResponseResult result = saveArticle3(wmNews);
        if (result.getCode() != 200) {
            return;
        }

        //5.修改wm_news表的状态
        wmNews.setArticleId((Long) result.getData());
        updateWmNews(wmNews, (short) 9, "发布成功");
    }

    /**
     * 自管理敏感词的审核业务方法
     *
     * @return
     */
    private boolean sensitiveScan(WmNews wmNews, String content) {
        //1.定义flag
        boolean flag = true;
        //2. 查询wm_sensitive表
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(null);
        //过滤只包含敏感词的list集合
        List<String> collect = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());

        //2.执行DFA算法，初始化敏感词库
        SensitiveWordUtil.initMap(collect);

        //3.匹配出现的次数，过滤是否包含敏感词
        Map<String, Integer> stringIntegerMap = SensitiveWordUtil.matchWords(content);
        //表示文章内容中出现了敏感词
        if (stringIntegerMap.size() > 0) {
            updateWmNews(wmNews, (short) 2, "文章内容中包含自定义敏感词");
            flag = false;
        }
        return flag;
    }


    /**
     * 抽取远程调用保存三剑客方法
     *
     * @param wmNews
     * @return
     */
    private ResponseResult saveArticle3(WmNews wmNews) {
        ArticleDto articleDto = new ArticleDto();
        //从wmnews实体类中把相关属性拷贝到articleDto对象中
        //属性的拷贝
        BeanUtils.copyProperties(wmNews, articleDto);
        //文章的布局
        articleDto.setLayout(wmNews.getType());
        //频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel != null) {
            articleDto.setChannelName(wmChannel.getName());
        }

        //作者
        articleDto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser != null) {
            articleDto.setAuthorName(wmUser.getName());
        }

        //设置文章id
        if (wmNews.getArticleId() != null) {
            articleDto.setId(wmNews.getArticleId());
        }
        articleDto.setCreatedTime(new Date());
        ResponseResult responseResult = articleFeignClient.saveAparticle(articleDto);
        return responseResult;
    }

    /**
     * 抽取审核图片的方法
     *
     * @param wmNews
     * @param imageList 包含所有的图片地址(文章内容中的图片和封面图片)
     * @return
     */
    private boolean imageScan(WmNews wmNews, List<String> imageList) {

        boolean flag = true;

        List<byte[]> imageByteList = new ArrayList<>();

        //2.要根据图片地址集合去下载图片流
        if (imageList != null && imageList.size() > 0) {
            //2.1 当前imageList中有可能会有重复图片地址，去重
            imageList = imageList.stream().distinct().collect(Collectors.toList());
            //2.2 遍历下载
            for (String path : imageList) {
                byte[] bytes = fileStorageService.downLoadFile(path);
                //图片ocr审核
                InputStream in = new ByteArrayInputStream(bytes);
                BufferedImage image = null;
                try {
                    image = ImageIO.read(in);
                    String resultText = tess4jClient.doOCR(image);
                    //进行自管理敏感词的审核
                    boolean sensitiveFlag = sensitiveScan(wmNews, resultText);
                    if (!sensitiveFlag) {
                        return false;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                imageByteList.add(bytes);
            }
        }
        //1.调用审核图片的方法
        try {
            Map scanImageMap = greenImageScan.imageScan(imageByteList);
            //违规，审核不通过
            if (scanImageMap.get("suggestion").equals("block")) {
                //修改wm_news表的状态
                updateWmNews(wmNews, (short) 2, "审核失败，图片包含敏感信息");
                flag = false;
            }
            //表示需要人工审核
            if (scanImageMap.get("suggestion").equals("review")) {
                //修改wm_news表的状态
                updateWmNews(wmNews, (short) 3, "图片中包含不确定信息，需要人工审核");
                flag = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;

    }

    /**
     * 抽取审核垃圾检测文本的方法
     *
     * @param wmNews
     * @param content
     * @return
     */
    private boolean textScan(WmNews wmNews, String content) {

        boolean flag = true;

        try {
            Map scanTextMap = greenTextScan.greeTextScan(content);
            //违规，审核不通过
            if (scanTextMap.get("suggestion").equals("block")) {
                //修改wm_news表的状态
                updateWmNews(wmNews, (short) 2, "审核失败，文本中包含敏感词");
                flag = false;
            }
            //表示需要人工审核
            if (scanTextMap.get("suggestion").equals("review")) {
                //修改wm_news表的状态
                updateWmNews(wmNews, (short) 3, "文本中包含不确定词汇，需要人工审核");
                flag = false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    /**
     * 修改wm_news表
     *
     * @param wmNews
     * @param status 文章状态
     * @param reason 失败原因
     */
    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 抽取的第一个方法：要对当前文本和图片进行抽取
     *
     * @param wmNews
     */
    private Map<String, Object> chouquImageAndTextFromWmNews(WmNews wmNews) {
        //1.定义一个字符串
        StringBuilder sb = new StringBuilder();
        sb.append(wmNews.getTitle());

        //2.定义一个list集合来承载图片地址
        List<String> imageUrlList = new ArrayList<>();

        //。解析文章内容
        String content = wmNews.getContent();
        List<Map> mapList = JSONArray.parseArray(content, Map.class);
        for (Map map : mapList) {
            //认为是文本内容
            if (map.get("type").equals("text")) {
                String textValue = (String) map.get("value");
                sb.append(textValue);
            }
            //图片
            if (map.get("type").equals("image")) {
                String imageUrlValue = (String) map.get("value");
                imageUrlList.add(imageUrlValue);
            }
        }
        //解析封面图片  "xxx.jpg,yyy.jpg"
        String images = wmNews.getImages();
        /**
         * imagUrlList=["xx.jpg","xxx.jpg", "xxx.jpg,yyy.jpg"]
         */
        String[] split = images.split(",");//["xxx.jpg","yyy.jpg"]
        imageUrlList.addAll(Arrays.asList(split));

        //封装数据
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("content", sb.toString());
        resultMap.put("imageList", imageUrlList);
        return resultMap;
    }

}
